#!/bin/bash

ROOT_DIR="/var/www/clients/client0/web23/web/xml"
CRASHES_FN="crashes_source.xml"
STATS_FN="stats_source.html"
CRASHES_NICE_FN="crashes_nice.xml"
TEXT_FN="../text.html"
CRASHES_URL="http://aplikace.policie.cz/dopravni-informace/GetFile.aspx"
STATS_URL="http://vdb.czso.cz/vdbvo/tabparam.jsp?voa=tabulka&cislotab=DOP0080UU+_KR&kapitola_id=40"

ERROR_FN="error.log"
ERROR=0

# $1 URL, $2 filename
function download {
    if ! wget -O $2 $1 &> /dev/null; then
        echo "Nastala chyba při stahování $1" >> $ERROR_FN
        exit
    fi
}

# $1 xml schema, $2 xml filename
function validate_xml {
    if ! xmllint --noout --schema $1 $2 &> /dev/null; then
        echo "Soubor $2 není validní" >> $ERROR_FN
        ERROR=1
    fi
}

# $1 output xml filename, $2 xsl filename, $3 input xml filename
function transform_xml {
    if ! xsltproc --noout -o $1 $2 $3 &> /dev/null;	then 
    	echo "Soubor $3 nelze transformovat" >> $ERROR_FN
    	ERROR=2
    fi
}

# $1 backup file
function backup {
    cp $1 $1"_old"
}

# $1 backup file; should be in pair with function backup
function backup_end {
    if [ $ERROR -eq 1 ]; then
        rm $1; mv $1"_old" $1
        ERROR=0
    elif [ $ERROR -eq 2 ]; then
        rm $1; mv $1"_old" $1
        exit
    else
        rm $1"_old"
    fi
}

# MAIN
cd $ROOT_DIR

# beginning of log entry
echo `date +"%d.%m.%Y %H:%M:%S"` >> $ERROR_FN

download $CRASHES_URL $CRASHES_FN
download $STATS_URL $STATS_FN

# crashes_source.xml to crashes_nice.xml
# backup of previously transformed file
backup $CRASHES_NICE_FN
validate_xml UglyXmlSchema.xsd $CRASHES_FN
transform_xml $CRASHES_NICE_FN uglytonice.xsl $CRASHES_FN
validate_xml NiceXmlSchema.xsd $CRASHES_NICE_FN
# if error occurs during validation or transformation, load backup
backup_end $CRASHES_NICE_FN

# crashes_nice.xml to text.html
backup $TEXT_FN
transform_xml $TEXT_FN NiceXmlToHtml.xsl $CRASHES_NICE_FN
backup_end $TEXT_FN

# end of log entry
echo -e "--------------------\n" >> $ERROR_FN
